<?php

namespace app\api\controller\v1;

use app\api\model\v1\UserCheck;
use app\api\model\v1\UserEnterprise;
use app\api\model\v1\UserStudent;
use app\api\model\v1\UserStudy;
use app\api\model\v1\UserTeacher;
use app\common\controller\Api;
use app\common\library\Sms as Smslib;
use \app\api\model\v1\User as UserModel;
use app\common\library\Sms;
use fast\Random;
use think\Config;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Validate;

class User extends Api
{
    protected $noNeedLogin = ['sendMsg','register','login','checkMsg','mobilelogin',
        'resetpwd','studentApply','teacherApply','checkApply','enterpriseApply','studyApply'];
    protected $noNeedRight = ['*'];
    public function _initialize()
    {
        parent::_initialize();

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }
        $this->user=model('admin/User');
        $this->check=model('admin/user/Check');

        $this->study=model('admin/user/Study');
        $this->student=model('admin/user/Student');
        $this->enterprise=model('admin/user/Enterprise');
        $this->teacher=model('admin/user/Teacher');


    }
    /**
     * 发送短信
     */
    public function sendMsg()
    {
        $mobile = $this->request->post("mobile");
        $event = $this->request->post("event");
        $event = $event ? $event : 'register';

        if (!$mobile || !\think\Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('手机号不正确'));
        }
        $last = Smslib::get($mobile, $event);
        if ($last && time() - $last['createtime'] < 60) {
            $this->error(__('发送频繁'));
        }
        $ipSendTotal = \app\common\model\Sms::where(['ip' => $this->request->ip()])->whereTime('createtime', '-1 hours')->count();
        if ($ipSendTotal >= 5) {
            $this->error(__('发送频繁'));
        }
        if ($event) {
            $userinfo = UserModel::where('mobile', $mobile)->find();
            if ($event == 'register' && $userinfo) {
                //已被注册
                $this->error(__('已被注册'));
            } elseif (in_array($event, ['changemobile']) && $userinfo) {
                //被占用
                $this->error(__('已被占用'));
            } elseif (in_array($event, ['changepwd', 'resetpwd']) && !$userinfo) {
                //未注册
                $this->error(__('未注册'));
            }
        }
        //发送验证码
        $ret = Smslib::setSend($mobile, null, $event);
        if ($ret) {
            $this->success(__('发送成功'));
        } else {
            $this->error(__('发送失败，请检查短信配置是否正确'));
        }
    }

    /**
     * 检验验证码
     */
    public function checkMsg()
    {
        $mobile = $this->request->post("mobile");
        $event = $this->request->post("event");
        $event = $event ? $event : 'register';
        $captcha = $this->request->post("captcha");

        if (!$mobile || !\think\Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('手机号不正确'));
        }
        if ($event) {
            $userinfo = UserModel::where('mobile', $mobile)->find();
            if ($event == 'register' && $userinfo) {
                //已被注册
                $this->error(__('已被注册'));
            } elseif (in_array($event, ['changemobile']) && $userinfo) {
                //被占用
                $this->error(__('已被占用'));
            } elseif (in_array($event, ['changepwd', 'resetpwd']) && !$userinfo) {
                //未注册
                $this->error(__('未注册'));
            }
        }
        $ret = Smslib::setCheck($mobile, $captcha, $event);
        if ($ret) {
            $this->success(__('成功'));
        } else {
            $this->error(__('验证码不正确'));
        }

    }

    /**
     * 注册
     */
    public function register()
    {
        $mobile = $this->request->post('mobile');
        $code = $this->request->post('code');
        $password = $this->request->post('password');
        $password_confirmation = $this->request->post('password_confirmation');
        $id_card = $this->request->post('id_card') ?? '';
        $invitation_code = $this->request->post('invitation_code','');

        if (!$mobile || !\think\Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('手机号不正确'));
        }

        //验证验证码
//        $ret = Sms::setCheck($mobile, $code, 'register');
//        if (!$ret) {
//            $this->error('验证码不正确');
//        }

        $validate = new Validate([
            'password' => 'require|alphaNum|min:5|confirm:password_confirmation',
        ], [
            'password.require' => '请输入密码',
            'password.alphaNum' => '密码只能包含字母和数字',
            'password.min' => '密码最少5位',
            'password.confirm' => '两次输入不一致',
        ]);
        $data = [
            'password' => $password,
            'password_confirmation' => $password_confirmation,
        ];
        if (!$validate->check($data)) {
            $this->error($validate->getError());
        }
        if ($id_card) {
            if (!isCreditNo($id_card)) {
                $this->error('身份证号不正确');
            }
        }

        $extend=[];
        if($invitation_code!=''){

            if($teacherInfo=Db::name('user_teacher')->where('invitation_code',$invitation_code)->find()){
                $extend['teacher_id']=$teacherInfo['id'];
            }else{
                $this->error('邀请老师不存在');
            }
          //  $extend['invitation_code']=$invitation_code;
        }
        //注册
        $ret = $this->auth->setRegister($mobile, $password, $id_card, $extend);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Sign up successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 用户登录
     */
    public function login()
    {
        $account = $this->request->post('account');
        $password = $this->request->post('password');

        $juese = $this->request->post('juese',1);

        if (!$account) {
            $this->error('请输入手机号或身份证号');
        }
        if (!$password) {
            $this->error('请输入密码');
        }

        $ret = $this->auth->setLogin($account, $password,$juese);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 手机验证码登录
     */
    public function mobilelogin()
    {
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        $juese = $this->request->post('juese','');

        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!$juese || $juese=='') {
            $this->error(__('请选择角色登录'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('手机号不正确'));
        }
        if (!Sms::setCheck($mobile, $captcha, 'mobilelogin')) {
            $this->error(__('验证码不正确'));
        }

        $user = \app\api\model\v1\User::where('mobile',$mobile)->where( " FIND_IN_SET($juese,juese_ids)")->find();
        if (!$user) $this->error('手机号不存在或该角色未入驻');
        if ($user->status != 'normal') {
            $this->error(__('Account is locked'));
        }
        //如果已经有账号则直接登录
        $ret = $this->auth->direct($user->id);
        if ($ret) {
            Sms::flush($mobile, 'mobilelogin');
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 重置密码
     */
    public function resetpwd()
    {
        $mobile = $this->request->post('mobile');
        $newpassword = $this->request->post("newpassword");
        $captcha = $this->request->post("captcha");
        if (!$mobile || !\think\Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('手机号不正确'));
        }
        //验证验证码
        $ret = Sms::setCheck($mobile, $captcha, 'resetpwd');
        if (!$ret) {
            $this->error('验证码不正确');
        }
        $validate = new Validate([
            'newpassword' => 'require|alphaNum|min:5',
        ], [
            'newpassword.require' => '请输入密码',
            'newpassword.alphaNum' => '密码只能包含字母和数字',
            'newpassword.min' => '密码最少5位',
        ]);
        $data = [
            'newpassword' => $newpassword,
        ];
        if (!$validate->check($data)) {
            $this->error($validate->getError());
        }
        $user = \app\api\model\v1\User::where('mobile',$mobile)->find();
        if (!$user) $this->error('手机号不存在');
        Sms::flush($mobile, 'resetpwd');
        //模拟一次登录
        $this->auth->direct($user->id);
        $ret = $this->auth->changepwd($newpassword, '', true);
        if ($ret) {
            $this->success(__('成功'));
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 学员入驻
     */
    public function studentApply()
    {

//        dump($this->auth->id);
//        exit;
//        if($this->auth->juese!=0){
//            $this->error('一个会员只能申请一个角色');
//        }
        $name = $this->request->post('name');
        $id_card = $this->request->post('id_card');
        $sex = $this->request->post('sex') ?? '男';
        $pinyin = $this->request->post('pinyin') ?? '';

        $oldname = $this->request->post('oldname') ?? '';
        $birthday = $this->request->post('birthday') ?? '';

        $minzu = $this->request->post('minzu') ?? '';
        $jiguan = $this->request->post('card_back_image') ?? '';

        $last_image = $this->request->post('last_image') ?? '';
        $mianmao = $this->request->post('mianmao') ?? '';

        $xueli = $this->request->post('xueli') ?? '';
        $major = $this->request->post('major') ?? '';

        $school = $this->request->post('school') ?? '';
        $comeinschool = $this->request->post('comeinschool') ?? '';
        $biye_school = $this->request->post('biye_school') ?? '';
        $address = $this->request->post('address') ?? '';

        $youbian = $this->request->post('youbian') ?? '';
        $contact_mobile = $this->request->post('contact_mobile') ?? '';
        $school_url = $this->request->post('school_url') ?? '';
        $chuanzhen = $this->request->post('chuanzhen') ?? '';

        $mobile = $this->request->post('mobile') ?? '';
        $email = $this->request->post('email') ?? '';
//        $nickname = $this->request->post('name') ?? '';

        $captcha = $this->request->post('captcha') ?? '';
        $biye_image = $this->request->post('biye_image') ?? '';

          $card_front_image=$this->request->post('card_front_image') ?? '';
        $card_back_image=$this->request->post('card_back_image') ?? '';

        $event = 'signup';
        if($mobile==null || $captcha==null){
            $this->error(__('手机号/短信验证码参数不全'));
        }

        if (!$mobile || !\think\Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('手机号不正确'));
        }
//        $juese='';
//        if($user_mobile=$this->user->where('mobile',$mobile)->find()){  //手机号已注册
//            if(in_array(1, explode(",",$user_mobile->juese_ids))){
//                $this->error(__('该手机号已入驻过学员'));
//            }else{
//                $juese=$user_mobile->juese_ids;
//            }
//
//        }
//
//
//        if($user_id_card=$this->user->where('id_card',$id_card)->find()){  //手机号已注册
//            if(in_array(1, explode(",",$user_id_card->juese_ids))){
//                $this->error(__('该手机号已入驻过学员'));
//            }else{
//                $juese=$user_id_card->juese_ids;
//            }
//
//        }






        if (!$name) {
            $this->error('请输入姓名');
        }
        if($this->auth->id==NUll){
            $check_mobile=checkUser($mobile,'','');
            if($check_mobile['code']==0){
                $this->error($check_mobile['msg']);
            }

            $check_id_card=checkUser('',$id_card,'');

            if($check_id_card['code']==0){
                $this->error($check_id_card['msg']);
            }
            Db::startTrans();
            try {




            $extend['juese_ids']=1;
            $extend['id_card']=$id_card;

            $ret = $this->auth->setRegister($name,$mobile, 'Aa123456', $id_card, $extend);
            if($ret['code']==0){
                $this->error($ret['msg']);
            }

         UserStudent::create([
                'user_id' => $this->auth->id,
                'name' => $name,
                'sex'=>$sex,
                'pinyin'=>$pinyin,
                'oldname'=>$oldname,
                'birthday'=>$birthday,
                 'minzu'=>$minzu,
                'jiguan'=>$jiguan,
                'last_image'=>$last_image,
                'mianmao'=>$mianmao,
                'xueli'=>$xueli,
                'major'=>$major,
                'school'=>$school,
                'biye_school'=>$biye_school,
                'comeinschool'=>$comeinschool,
                'address'=>$address,
                'youbian'=>$youbian,
                'contact_mobile'=>$contact_mobile,
                'school_url'=>$school_url,
                'chuanzhen'=>$chuanzhen,
                'biye_image'=>$biye_image,
                'id_card' => $id_card,
                'card_front_image' => $card_front_image,
                'card_back_image' => $card_back_image,
                'status' => 0,
               'email'=>$email,
            ]);
                Db::commit();
                $data=['token'=>$this->auth->getToken(),'juese_ids'=>1];
                $this->success('提交成功',$data);
            } catch (ValidateException|PDOException|Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }


        }else{

           $juese_ids_arr= explode(",",$this->auth->juese_ids);
         if( in_array(1,$juese_ids_arr)){
             $this->error('您已入驻学员，不需要重新入驻');
         }
            $juese_ids_arr[]=1;
            $juese_ids_arr_str=implode(",",$juese_ids_arr);
           $this->user->where('id',$this->auth->id)->update(['juese_ids'=>$juese_ids_arr_str,'id_card'=>$id_card]);
            Db::startTrans();
            try {
                UserStudent::create([
                    'user_id' => $this->auth->id,
                    'name' => $name,
                    'sex'=>$sex,
                    'pinyin'=>$pinyin,
                    'oldname'=>$oldname,
                    'birthday'=>$birthday,
                    'minzu'=>$minzu,
                    'jiguan'=>$jiguan,
                    'last_image'=>$last_image,
                    'mianmao'=>$mianmao,
                    'xueli'=>$xueli,
                    'major'=>$major,
                    'school'=>$school,
                    'biye_school'=>$biye_school,
                    'comeinschool'=>$comeinschool,
                    'address'=>$address,
                    'youbian'=>$youbian,
                    'contact_mobile'=>$contact_mobile,
                    'school_url'=>$school_url,
                    'chuanzhen'=>$chuanzhen,
                    'biye_image'=>$biye_image,
                    'id_card' => $id_card,
                    'card_front_image' => $card_front_image,
                    'card_back_image' => $card_back_image,
                    'status' => 0,
                    'email'=>$email,
                ]);

                Db::commit();
                $this->success('提交成功');
            } catch (ValidateException|PDOException|Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }


        }


    }

    /**
     * 检测用户入驻过的角色
     */
    public function checkUserjuese(){

        $this->success('OK',$this->auth->juese_ids);
    }

    /**
     * 学习中心入驻
     */
    public function studyApply()
    {

        $name = $this->request->post('name');
        $legal_person = $this->request->post('legal_person');
        $set_date = $this->request->post('set_date') ?? '';
        $price = $this->request->post('price') ?? '';
        $address = $this->request->post('address') ?? '';
        $image = $this->request->post('image') ?? '';
//        $type = $this->request->post('type') ?? 'study';
        $category = $this->request->post('category'); //所属分类:1=免费执照,2=法律服务,3=知识产权,4=共享办公
        $user_check_ids = $this->request->post('user_check_ids'); //入驻机构IDS
        $user_check_ids = trim($user_check_ids, ',');
        $mobile = $this->request->post('mobile');
        $zuzhi_code=$this->request->post('zuzhi_code');

        $credit_image=$this->request->post('credit_image');
        if (!$name) $this->error('请输入单位名称');
        if (!$legal_person) $this->error('请输入法定代表人');
        if (!$set_date) $this->error('请输入成立时间');
        if (!$price) $this->error('请输入注册资金');
        if (!$address) $this->error('请输入单位地址');
        if (!$image) $this->error('请上传资质证书');
        if (empty($category)) $this->error('请选择分类');
        if (empty($user_check_ids)) $this->error('请选择入驻机构');
        if($this->auth->id!=NULL){
            Db::startTrans();
            try {

                $check_mobile=checkUser($mobile,'','');
                if($check_mobile['code']==0){
                    $this->error($check_mobile['msg']);
                }

                $check_id_card=checkUser('','','','',$zuzhi_code);
                if($check_id_card['code']==0){
                    $this->error($check_id_card['msg']);
                }
                $extend['juese_ids']=5;
                $extend['zuzhi_code']=$zuzhi_code;
                $ret = $this->auth->setRegister($name,$mobile, 'Aa123456', '', $extend);
                if($ret['code']==0){
                    $this->error($ret['msg']);
                }



                UserStudy::create([
                    'user_id' => $this->auth->id,
                    'name' => $name,
                    'legal_person' => $legal_person,
                    'set_date' => $set_date,
                    'price' => $price,
                    'address' => $address,
                    'image' => $image,
                    'status' => 0,
                    'category' => $category,
                    'user_check_ids' => $user_check_ids,
                    'zuzhi_code'=>$zuzhi_code,
                    'credit_image'=>$credit_image,
                ]);

                $data=['token'=>$this->auth->getToken(),'juese_ids'=>5];
                Db::commit();
                $this->success('OK',$data);
            } catch (ValidateException|PDOException|Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
        }else{
            Db::startTrans();
            try {

                $juese_ids_arr= explode(",",$this->auth->juese_ids);
            if(in_array(5,$juese_ids_arr)){
                $this->error('企业您已入驻，无需重新提交');
            }
            $juese_ids_arr[]=5;
            $juese_ids_str=implode(",",$juese_ids_arr);
            $this->user->where('id',$this->auth->id)->update(['juese_ids'=>$juese_ids_str,'zuzhi_code'=>$zuzhi_code]);

            UserStudy::create([
                'user_id' => $this->auth->id,
                'name' => $name,
                'legal_person' => $legal_person,
                'set_date' => $set_date,
                'price' => $price,
                'address' => $address,
                'image' => $image,
                'status' => 0,
                'category' => $category,
                'user_check_ids' => $user_check_ids,
                'zuzhi_code'=>$zuzhi_code,
                'credit_image'=>$credit_image,
            ]);
                Db::commit();
                $this->success('OK');
            } catch (ValidateException|PDOException|Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
        }


    }

    /**
     * 考评机构入驻
     */
    public function checkApply()
    {
//         if($this->auth->juese!=0){
//            $this->error('一个会员只能申请一个角色');
//        }
        $name = $this->request->post('name');
        $legal_person = $this->request->post('legal_person');
        $set_date = $this->request->post('set_date') ?? '';
        $price = $this->request->post('price') ?? '';
        $address = $this->request->post('address') ?? '';
        $image = $this->request->post('image') ?? '';
        $type = $this->request->post('type') ?? 'check';
        $zuzhi = $this->request->post('zuzhi') ?? 'zuzhi';
        $mobile=$this->request->post('mobile');
        $captcha=$this->request->post('captcha');
        $yingyezhizhao_image = $this->request->post('yingyezhizhao_image') ?? 'yingyezhizhao_image';

        if (!$name) $this->error('请输入单位名称');
        if (!$legal_person) $this->error('请输入法定代表人');
        if (!$set_date) $this->error('请输入成立时间');
        if (!$price) $this->error('请输入注册资金');
        if (!$address) $this->error('请输入单位地址');
        if (!$image) $this->error('请上传资质证书');
        if (!$yingyezhizhao_image) $this->error('请上传营业执照');
        if (!$zuzhi) $this->error('组织机构代码必须填写');

        $event = 'signup';
        if($mobile==null || $captcha==null){
            $this->error(__('手机号/短信验证码参数不全'));
        }

        if (!$mobile || !\think\Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('手机号不正确'));
        }

        if($this->auth->id==NULL){


            $check_mobile=checkUser($mobile,'','');
          //  dump($check_mobile);

            if($check_mobile['code']==0){
                $this->error($check_mobile['msg']);
            }

            $check_id_card=checkUser('','',$zuzhi);

            if($check_id_card['code']==0){
                $this->error($check_id_card['msg']);
            }
            //1:学员 2:名师:3:实训基地4:评价中心;5学习中心;6考核机构;7:企业
            //入驻类型:check=主考机构,evaluation=评价中心,base=实训基地
            if($type=='check'){

                $juese_ids=6;
            }elseif($type=='evaluation'){
                $juese_ids=4;
            }elseif($type=='base'){
                $juese_ids=3;
            }
            $extend['juese_ids']=$juese_ids;
            $extend['zuzhi']=$zuzhi;
//            $extend['yingyezhizhao_image']=$yingyezhizhao_image;
            Db::startTrans();
            try {
            $ret = $this->auth->setRegister($name,$mobile, 'Aa123456', '', $extend);

            UserCheck::create([
                'user_id' => $this->auth->id,
                'name' => $name,
                'legal_person' => $legal_person,
                'set_date' => $set_date,
                'price' => $price,
                'address' => $address,
                'image' => $image,
                'status' => 0,
                'type' => $type,
                'zuzhi'=>$zuzhi,
                'yingyezhizhao_image'=>$yingyezhizhao_image,

            ]);
                $data=['token'=>$this->auth->getToken(),'juese_ids'=>$juese_ids];
                Db::commit();
                $this->success('OK',$data);
            } catch (ValidateException|PDOException|Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
        }else{
            Db::startTrans();
            try {
               $juese_ids_arr= explode(",",$this->auth->juese_ids);

                if($type=='check'){
                    $juese_ids=6;
                }elseif($type=='evaluation'){
                    $juese_ids=4;
                }elseif($type=='base'){
                    $juese_ids=3;
                }

               if(in_array($juese_ids,$juese_ids_arr)){
                $this->error('您注册过考核机构，且只能申请一种机构，请勿重复申请');
               }

                $juese_ids_arr[]=$juese_ids;
                $juese_ids_str=implode(",",$juese_ids_arr);
               $this->user->where('id',$this->auth->id)->update(['juese_ids'=>$juese_ids_str,'zuzhi'=>$zuzhi]);

                UserCheck::create([
                    'user_id' => $this->auth->id,
                    'name' => $name,
                    'legal_person' => $legal_person,
                    'set_date' => $set_date,
                    'price' => $price,
                    'address' => $address,
                    'image' => $image,
                    'status' => 0,
                    'type' => $type,
                    'zuzhi'=>$zuzhi,
                    'yingyezhizhao_image'=>$yingyezhizhao_image,
                ]);

                Db::commit();
                $this->success('申请成功');
            } catch (ValidateException|PDOException|Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
        }
    }

    /**
     * 企业入驻
     */
    public function enterpriseApply()
    {

        $name = $this->request->post('name');
        $credit_code = $this->request->post('credit_code');
        $legal_person = $this->request->post('legal_person');
        $register_office = $this->request->post('register_office') ?? '';
        $register_address = $this->request->post('register_address') ?? '';
        $business_address = $this->request->post('business_address') ?? '';
        $business_range = $this->request->post('business_range') ?? '';
        $username = $this->request->post('username');
        $mobile = $this->request->post('mobile');
        $category = $this->request->post('category') ?? '1';
        $desc = $this->request->post('desc');
        $set_date = $this->request->post('set_date') ?? '';
        $price = $this->request->post('price') ?? '';
        $credit_image=$this->request->post('credit_image') ?? '';
        if (!$name) $this->error('请输入名称');
        if (!$credit_code) $this->error('请输入统一社会信用代码');
        if (!$credit_image) $this->error('请上传营业执照');
        if (!$legal_person) $this->error('请输入法人');
        if (!$business_address) $this->error('请输入经营地址');
        if (!$username) $this->error('请输入联系人');
        if (!$mobile || !\think\Validate::regex($mobile, "^1\d{10}$")) {
            $this->error('请输入联系方式');
        }
        if (!$set_date) $this->error('请输入成立时间');
        if (!$price) $this->error('请输入注册资金');
//        $userModel = $this->auth->getUser();
//        if ($userModel->identity) {
//            $this->error('已入驻成功');
//        }
//        if ($res = UserEnterprise::where('user_id', $userModel->id)->where('status', '=', '0')->find()) {
//            $this->error('请等待审核');
//        }

        if($this->auth->id==NULL){
            Db::startTrans();
            try {

                $check_mobile=checkUser($mobile,'','');
                if($check_mobile['code']==0){
                    $this->error($check_mobile['msg']);
                }
                $check_id_card=checkUser('','','',$credit_code);
                if($check_id_card['code']==0){
                    $this->error($check_id_card['msg']);
                }
                $extend['juese_ids']=7;
                $extend['credit_code']=$credit_code;
                $ret = $this->auth->setRegister($name,$mobile, 'Aa123456', '', $extend);
                if($ret['code']==0){
                    $this->error($ret['msg']);
                }
                UserEnterprise::create([
                    'user_id' => $this->auth->id,
                    'name' => $name,
                    'credit_code' => $credit_code,
                    'legal_person' => $legal_person,
                    'register_office' => $register_office,
                    'register_address' => $register_address,
                    'business_address' => $business_address,
                    'business_range' => $business_range,
                    'username' => $username,
                    'mobile' => $mobile,
                    'status' => 0,
                    'category' => $category,
                    'desc' => $desc,
                    'set_date' => $set_date,
                    'price' => $price,
                    'credit_image'=>$credit_image,
                ]);

                $data=['token'=>$this->auth->getToken(),'juese_ids'=>7];
                Db::commit();
                $this->success('OK',$data);
            } catch (ValidateException|PDOException|Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
        }else{
            Db::startTrans();
            try {

                $juese_ids=explode(",",$this->auth->juese_ids);
            if(in_array($juese_ids,[7])){
                $this->error('您注册入驻过企业，请勿重复申请');
            }
            $juese_ids_arr[]=7;
            $juese_ids_str=implode(",",$juese_ids_arr);
            $this->user->where('id',$this->auth->id)->update(['juese_ids'=>$juese_ids_str,'credit_code'=>$credit_code]);
            UserEnterprise::create([
                'user_id' => $this->auth->id,
                'name' => $name,
                'credit_code' => $credit_code,
                'legal_person' => $legal_person,
                'register_office' => $register_office,
                'register_address' => $register_address,
                'business_address' => $business_address,
                'business_range' => $business_range,
                'username' => $username,
                'mobile' => $mobile,
                'status' => 0,
                'category' => $category,
                'desc' => $desc,
                'set_date' => $set_date,
                'price' => $price,
                'credit_image'=>$credit_image,
            ]);
                Db::commit();
                $this->success('OK');
            } catch (ValidateException|PDOException|Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }

        }

    }
    
    /**
     * 名师入驻
     */
    public function teacherApply()
    {

        $name = $this->request->post('name');
        $id_card = $this->request->post('id_card');
        $major = $this->request->post('major');
        $image = $this->request->post('image');
        $issue_unit = $this->request->post('issue_unit');
        $teaching = $this->request->post('teaching');
        $teaching_major = $this->request->post('teaching_major');
        $unit = $this->request->post('unit');
        $teacher_status = $this->request->post('teacher_status');
        $address = $this->request->post('address') ?? '';
        $username = $this->request->post('name');
        $mobile = $this->request->post('mobile');
        $retire_image = $this->request->post('retire_image') ?? ''; //退休证
        $unit_image = $this->request->post('unit_image') ?? ''; //单位同意证明
        $user_image = $this->request->post('user_image'); //个人照片
        $card_front_image = $this->request->post('card_front_image'); //身份证正面
        $card_back_image = $this->request->post('card_back_image'); //身份证反面
        if (!$name) $this->error('请输入姓名');
        if (!$id_card || !isCreditNo($id_card)) {
            $this->error('请输入有效的身份证号');
        }
        if (!$major) $this->error('请输入专业方向');
        if (!$image) $this->error('请上传资质证书');
        if (!$issue_unit) $this->error('请输入颁发资质单位');
        if (!$teaching) $this->error('请输入授课方向');
        if (!$teaching_major) $this->error('请输入所授专业');
        if (!$unit) $this->error('请输入所属单位');
        if (empty($teacher_status)) $this->error('请选择状态');
        if (!$username) $this->error('请输入联系人');
        if (!$mobile || !\think\Validate::regex($mobile, "^1\d{10}$")) {
            $this->error('请输入联系方式');
        }
        if ($teacher_status == 1 && !$unit_image) {
            $this->error('请上传单位同意证明');
        }
        if ($teacher_status == 3 && !$retire_image) {
            $this->error('请上传退休证');
        }
        if (!$user_image) {
            $this->error('请上传个人照片');
        }
        if (!$card_front_image) {
            $this->error('请上传身份证人像面');
        }
        if (!$card_back_image) {
            $this->error('请上传身份证国徽面');
        }
//        $userModel = $this->auth->getUser();
//        if ($userModel->identity) {
//            $this->error('已入驻成功');
//        }
//        if ($res = UserTeacher::where('user_id', $userModel->id)->where('status', '=', '0')->find()) {
//            $this->error('请等待审核');
//        }


    if($this->auth->id==NULL){
        Db::startTrans();
        try {
        $check_mobile=checkUser($mobile,'','');
        if($check_mobile['code']==0){
            $this->error($check_mobile['msg']);
        }
        $check_id_card=checkUser('',$id_card,'');

        if($check_id_card['code']==0){
            $this->error($check_id_card['msg']);
        }

        $extend['juese_ids']=2;
        $extend['id_card']=$id_card;
        $ret = $this->auth->setRegister($name,$mobile, 'Aa123456', $id_card, $extend);
        if($ret['code']==0){
            $this->error($ret['msg']);
        }

        UserTeacher::create([
            'user_id' => $this->auth->id,
            'name' => $name,
            'id_card' => $id_card,
            'major' => $major,
            'image' => $image,
            'issue_unit' => $issue_unit,
            'teaching' => $teaching,
            'teaching_major' => $teaching_major,
            'unit' => $unit,
            'teacher_status' => $teacher_status,
            'address' => $address,
            'username' => $username,
            'mobile' => $mobile,
            'status' => 0,
            'retire_image' => $retire_image,
            'unit_image' => $unit_image,
            'user_image' => $user_image,
            'card_front_image' => $card_front_image,
            'card_back_image' => $card_back_image,
        ]);
        $data=['token'=>$this->auth->getToken(),'juese_ids'=>2];

            Db::commit();
            $this->success('提交成功',$data);
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }

    }else{
        Db::startTrans();
        try {
            $juese_ids=explode(",",$this->auth->juese_ids);
        if(in_array($juese_ids,[2])){
            $this->error('您注册入驻过名师，请勿重复申请');
        }
        $juese_ids_arr[]=2;
        $juese_ids_str=implode(",",$juese_ids_arr);
        $this->user->where('id',$this->auth->id)->update(['juese_ids'=>$juese_ids_str,'id_card'=>$id_card]);

            UserTeacher::create([
                'user_id' => $this->auth->id,
                'name' => $name,
                'id_card' => $id_card,
                'major' => $major,
                'image' => $image,
                'issue_unit' => $issue_unit,
                'teaching' => $teaching,
                'teaching_major' => $teaching_major,
                'unit' => $unit,
                'teacher_status' => $teacher_status,
                'address' => $address,
                'username' => $username,
                'mobile' => $mobile,
                'status' => 0,
                'retire_image' => $retire_image,
                'unit_image' => $unit_image,
                'user_image' => $user_image,
                'card_front_image' => $card_front_image,
                'card_back_image' => $card_back_image,
            ]);
            Db::commit();
            $this->success('提交成功');
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
    }





    }
}